package com.ruoyi.web.easytron;

import lombok.extern.slf4j.Slf4j;
import com.ruoyi.web.easytron.handler.TransferHandlerContext;
import com.ruoyi.web.easytron.handler.Trc10TransferHandler;
import com.ruoyi.web.easytron.handler.Trc20TransferHandler;
import com.ruoyi.web.easytron.handler.TrxTransferHandler;
import com.ruoyi.web.easytron.model.ReferenceBlock;
import com.ruoyi.web.easytron.model.Transfer;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.exceptions.IllegalException;
import org.tron.trident.proto.Chain;
import org.tron.trident.utils.Convert;

import java.math.BigDecimal;

@Slf4j
public class BaseTest {

    /**
     * 私钥
     */
    public static String key = "6b898e92660728467e9bd3117f3b37ed026e607032570d0e2ec63de2f2854e09";
    /**
     * trident API 包装器
     */
    public static ApiWrapper wrapper = ApiWrapper.ofNile(key);
    /**
     * 转出地址
     */
    public static String from = wrapper.keyPair.toBase58CheckAddress();
    /**
     * 到账地址
     */
    public static String to = "TVwrimU7uKcVJx5oVaJrBcy6bwoDjbaEUU";
    /**
     * TRC20合约地址
     */
    public static String contractAddress = "TCLaGYqTsjWtwmXVs8r2J4jiYEoZk6xEX2";


    /**
     * 获取引用区块
     *
     * @param wrapper trident api
     * @return 引用区块信息
     * @throws IllegalException 参数错误
     */
    public static ReferenceBlock getReferenceBlock(ApiWrapper wrapper) throws IllegalException {
        // api 获取最新块
        Chain.Block nowBlock = wrapper.getNowBlock();
        return new ReferenceBlock(nowBlock.getBlockHeader());
    }


    /**
     * 创建TRC20转账
     */
    public static Transfer createTrc20Transfer(String from, String to, BigDecimal amount) {
        // 手续费限制，单位sum
        long feeLimit = Convert.toSun(BigDecimal.valueOf(50), Convert.Unit.TRX).longValue();
        return Transfer.trc20TransferBuilder(from, to, amount, contractAddress).feeLimit(feeLimit).memo("备注：TRC20转账").build();
    }

    /**
     * 发送构造好的交易
     *
     * @param transaction 交易
     */
    public static void sendTransaction(Chain.Transaction transaction) {
        // 签名
        Chain.Transaction signTransaction = wrapper.signTransaction(transaction);
        // 广播
        String tid = wrapper.broadcastTransaction(signTransaction);
        // 打印交易ID
        log.debug("交易ID：{}", tid);
    }

    /**
     * 转账处理器上下文
     */
    public static TransferHandlerContext createTransferHandlerContext() {
        TransferHandlerContext context = new TransferHandlerContext();
        context.addHandler(TrxTransferHandler.class.getName(), new TrxTransferHandler());
        context.addHandler(Trc20TransferHandler.class.getName(), new Trc20TransferHandler());
        context.addHandler(Trc10TransferHandler.class.getName(), new Trc10TransferHandler());
        return context;
    }
}

